<template>
  <div class="user-management-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>用户管理</h2>
      <p>分页查看所有用户信息，支持删除操作</p>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-state">
      <el-loading-spinner size="50"></el-loading-spinner>
      <p class="loading-text">加载用户数据中...</p>
    </div>

    <!-- 表格区域（加载完成且有数据） -->
    <div v-else class="table-section">
      <!-- 空状态处理 -->
      <el-empty
          v-if="users.length === 0"
          description="暂无用户数据"
          class="empty-state"
      />

      <!-- 用户表格 -->
      <el-table
          v-else
          :data="users"
          border
          stripe
          :header-cell-style="{ 'text-align': 'center', 'font-weight': '500' }"
          :cell-style="{ 'text-align': 'center' }"
          class="user-table"
      >
        <el-table-column
            prop="id"
            label="用户ID"
            width="80"
            align="center"
        />
        <el-table-column
            prop="nickName"
            label="用户昵称"
            width="140"
            align="center"
        />
        <el-table-column
            prop="loginName"
            label="登录名"
            width="140"
            align="center"
        />
        <el-table-column
            prop="email"
            label="邮箱"
            min-width="200"
            align="center"
        />
        <el-table-column
            prop="score"
            label="用户积分"
            width="100"
            align="center"
        />
        <el-table-column
            prop="role"
            label="用户角色"
            width="120"
            align="center"
        >
          <template #default="scope">
            <el-tag :type="scope.row.role === 1 ? 'success' : 'info'">
              {{ scope.row.role === 1 ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            label="操作"
            width="120"
            align="center"
        >
          <template #default="scope">
            <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="handleDelete(scope.row.id)"
                :disabled="scope.row.role === 1">  <!-- 禁止删除管理员 -->
            删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 30]"
            :total="totalUsers"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            background
        />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import {
  ElTable,
  ElTableColumn,
  ElPagination,
  ElEmpty,
  ElButton,
  ElTag,
  ElIcon,
  ElMessage,
  ElMessageBox
} from 'element-plus';
import { Delete, Loading } from '@element-plus/icons-vue';
import axios from '../api/index.js'; // 复用项目已配置的axios实例

export default {
  name: 'UserManagement',
  components: {
    ElTable,
    ElTableColumn,
    ElPagination,
    ElEmpty,
    ElButton,
    ElTag,
    ElIcon,
    Delete,
    Loading
  },
  setup() {
    // 1. 状态管理（分页、数据、加载状态）
    const currentPage = ref(1); // 当前页码（默认1）
    const pageSize = ref(10);   // 每页条数（默认10）
    const users = ref([]);      // 用户列表数据
    const totalUsers = ref(0);  // 总用户数
    const loading = ref(false); // 加载状态

    // 2. 核心方法：获取用户分页数据
    const fetchUsers = async () => {
      try {
        loading.value = true;
        const response = await axios.get('/admin/users', {
          params: {
            pageNum: currentPage.value,
            pageSize: pageSize.value
          }
        });
        // 后端返回数据已拦截处理，直接取data
        users.value = response.records || []; // 用户列表
        totalUsers.value = response.total || 0; // 总条数
      } catch (error) {
        console.error('获取用户数据失败:', error);
        ElMessage.error('加载用户失败，请稍后重试');
        users.value = [];
        totalUsers.value = 0;
      } finally {
        loading.value = false;
      }
    };

    // 3. 删除用户方法
    const handleDelete = async (userId) => {
      // 弹出确认框
      ElMessageBox({
        title: '确认删除',
        message: '此操作将永久删除该用户，是否继续？',
        type: 'danger',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        async onConfirm() {
          try {
            // 调用删除接口（注：后端删除接口参数应为用户ID，此处修正原文档笔误）
            await axios.post('/admin/delete', {
              params: { id: userId } // 传递用户ID作为删除参数
            });
            // 删除成功：刷新当前页数据
            ElMessage.success('用户删除成功');
            await fetchUsers();
          } catch (error) {
            console.error('删除用户失败:', error);
            ElMessage.error('删除用户失败，请稍后重试');
          }
        }
      });
    };

    // 4. 分页事件处理
    // 页大小改变
    const handleSizeChange = (val) => {
      pageSize.value = val;
      currentPage.value = 1; // 重置为第一页
      fetchUsers();
    };
    // 当前页码改变
    const handleCurrentChange = (val) => {
      currentPage.value = val;
      fetchUsers();
    };

    // 5. 组件初始化：默认加载第一页数据
    onMounted(() => {
      fetchUsers();
    });

    return {
      currentPage,
      pageSize,
      users,
      totalUsers,
      loading,
      fetchUsers,
      handleDelete,
      handleSizeChange,
      handleCurrentChange
    };
  }
};
</script>

<style scoped>
.user-management-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 24px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.page-header {
  margin-bottom: 24px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.page-header h2 {
  font-size: 20px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.page-header p {
  font-size: 14px;
  color: #666;
}

.loading-state {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 80px 0;
}

.loading-text {
  margin-top: 16px;
  font-size: 14px;
  color: #666;
}

.table-section {
  margin-top: 16px;
}

.empty-state {
  padding: 60px 0;
}

.user-table {
  width: 100%;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-top: 16px;
}

/* 响应式适配 */
@media (max-width: 768px) {
  .user-management-container {
    padding: 16px;
  }

  .pagination-container {
    justify-content: center;
  }

}
</style>